// @flow
import React from 'react'
import { Popover, Button, Checkbox, message } from 'antd'
import SelectTree from './SelectTree'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const CheckboxGroup = Checkbox.Group
// const RadioGroup = Radio.Group
import { connect } from 'react-redux'
import { changeHistoryChartCond } from 'store/modules/deviceFileCondition'
import styles from './SelectIndicator.css'

import type { Location } from 'react-router'
const { search } = location
const paramsString = search.substring(1)
const searchParams = new URLSearchParams(paramsString)
const requestType = searchParams.get('requestType')

type Props = {
  location: Location,
  changeHistoryChartCond: Function,
  deviceCard: Object,
  saveSelectedMonitors: Function,
  deviceFileCondition: Object,
  callback: Function,
  dynamicIndicator: Array<string>,
  defaultChannel: Array<string>,
  keyName: Array<string>,
  IndicatorEmpty: boolean
}

type State = {
  visible: boolean,
  deviceId: number,
  kmxMonitors: Array<any>,
  defaultValue: Array<Object>,
  treeData: Array<Object>,
  keyNameValue: string,
  sensorChannel: Array<Object>,
  sensorChannelId: Object
}

class SelectIndicator extends React.Component {
  props: Props
  state: State
  handleVisibleChange: Function
  refer: Function
  onChanges: Function
  keyNameChange: Function
  saveSelectedMonitors: Function
  changeDynamicCond: Function
  changeDynamicCondDefault: Function
  sensorChannelChange: Function
  setCurrentVaule: Function
  currentValue: string
  oldValue: string
  constructor (props: Object) {
    super(props)
    this.state = {
      visible: false,
      deviceId: this.props.deviceCard.deviceData.id,
      kmxMonitors: [],
      defaultValue: [],
      treeData: [],
      keyNameValue: this.props.keyName[0] || '',
      sensorChannel: [],
      sensorChannelId: {}
    }
    this.handleVisibleChange = this.handleVisibleChange.bind(this)
    this.refer = this.refer.bind(this)
    this.onChanges = this.onChanges.bind(this)
    this.keyNameChange = this.keyNameChange.bind(this)
    this.changeDynamicCond = this.changeDynamicCond.bind(this)
    this.changeDynamicCondDefault = this.changeDynamicCondDefault.bind(this)
    this.setCurrentVaule = this.setCurrentVaule.bind(this)
    this.sensorChannelChange = this.sensorChannelChange.bind(this)
  }

  componentWillMount () {
    const { IndicatorEmpty } = this.props
      // 指标列表
    let api = `${__SERVICE_API__}`
    if (requestType === 'wx') {
      api = `${__WXSERVICE_API__}`
    }
    universalFetch(`${api}device/devices/${this.state.deviceId}/monitors?group&varibleIsTemplate=1`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        const dynamicIndicator = this.props.dynamicIndicator
        let tap = true
        if (dynamicIndicator[0] === '') {
          tap = true
        } else {
          tap = false
        }
        let defaultValue = []
        this.setState({
          treeData: Object.keys(result).reduce((data, d, i) => {
            const items = Object.keys(result[d]).map((data, index) => {
              return {
                'title': data,
                'key': data,
                'children':result[d][data]
                  .filter((dd) => dd.kmxVariableNameEn !== 'channel_id')
                  .map((dd, ii) => {
                    if (!tap) {
                      dynamicIndicator.map((d, i) => {
                        const inds = d.split('___')
                        if (inds[0] === dd.sensorNameEn && inds[1] === dd.kmxVariableNameEn) {
                          defaultValue.push({
                            En: dd.sensorNameEn,
                            sensorType: dd.sensorType,
                            key: [dd.sensorNameEn + '___' + dd.kmxVariableNameEn],
                            keyName: [{ key:dd.sensorNameEn + '___' + dd.kmxVariableNameEn, name: dd.variableName }]
                          })
                        }
                      })
                    } else if (!IndicatorEmpty) {
                      // 默认选中第一个
                      if (ii === 0 && defaultValue.length === 0) {
                        defaultValue.push({
                          En: dd.sensorNameEn,
                          sensorType: dd.sensorType,
                          key: [dd.sensorNameEn + '___' + dd.kmxVariableNameEn],
                          keyName: [{ key:dd.sensorNameEn + '___' + dd.kmxVariableNameEn, name: dd.variableName }]
                        })
                      }
                      // 默认选振动量的derec
                      if (dd.sensorNameEn === 'c_vib' && dd.kmxVariableNameEn === 'direc') {
                        defaultValue.splice(0, defaultValue.length)
                        defaultValue.push({
                          En: dd.sensorNameEn,
                          sensorType: dd.sensorType,
                          key: [dd.sensorNameEn + '___' + dd.kmxVariableNameEn],
                          keyName: [{ key:dd.sensorNameEn + '___' + dd.kmxVariableNameEn, name: dd.variableName }]
                        })
                      }
                    }
                    return {
                      'title': dd.variableName,
                      'key': dd.kmxVariableNameEn,
                      'keyName':dd.variableName,
                      'sensorNameEn':dd.sensorNameEn,
                      'sensorType': dd.sensorType
                    }
                  })
              }
            })
            this.setState({
              defaultValue
            })
            data.push(...items)
            return data
          }, [])
        }, () => {
          // 通道
          let api = `${__SERVICE_API__}`
          if (requestType === 'wx') {
            api = `${__WXSERVICE_API__}`
          }
          universalFetch(`${api}device/devices/${this.state.deviceId}/channel-ids`)
            .then((res) => res.json())
            .then((json) => {
              if (json.code !== 200000) {
                throw new Error(JSON.stringify({ code: json.code, message: json.message }))
              }
              // 如果有默认通道就设置， 没有就设置为第一个
              const defaultChannel = this.props.defaultChannel
              const dynamicIndicator = this.props.dynamicIndicator
              let tap1 = true
              if (defaultChannel[0] === '') {
                tap1 = true
              } else {
                tap1 = false
              }
              let obj = {}
              if (!tap1) {
                json.result.map((d) => {
                  if (dynamicIndicator.length > 0) {
                    const inds = dynamicIndicator[0].split('___')[0]
                    if (inds === d.fieldGroup) {
                      obj[d.sensorType] = defaultChannel
                    }
                  }
                })
              } else if (!IndicatorEmpty) {
                json.result.map((d) => {
                  obj[d.sensorType] = [d.channelIds[0]['id'] + '__' + d.channelIds[0]['name']]
                })
              }
              this.setState({
                sensorChannel: json.result,
                sensorChannelId: Object.assign({}, this.state.sensorChannelId, obj)
              }, () => {
                this.changeDynamicCondDefault()
              })
            })
            .catch((error) => {
              handleFetchError(error)
              console.error(error)
            })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  // componentWillReceiveProps (nextProps) {
  //   if (!R.equals(nextProps, this.props)) {
  //     this.setState({
  //       sensorChannelId: {
  //         '振动量': ['3__烟排VE4214'],
  //         '过程量': ['3__烟排VE4214']
  //       }
  //     })
  //     console.log(nextProps);
  //   }
  // }

  refer () {
    this.setState({ visible: false })
    this.changeDynamicCond()
  }

  handleVisibleChange (visible) {
    this.setState({ visible })
  }
  changeDynamicCondDefault () {
    const callback = this.props.callback
    const { defaultValue, keyNameValue, sensorChannelId } = this.state
    let valuesType = []
    defaultValue.map((d, i) => {
      if (sensorChannelId[d.sensorType]) {
        valuesType.push({
          En: d.En,
          sensorType: d.sensorType,
          key: d.key.map((dd, ii) => {
            return dd.split('___')[1]
          }),
          channelIds: sensorChannelId[d.sensorType].map((d, i) => {
            return d.split('__')[0]
          }),
          channelNames: sensorChannelId[d.sensorType].map((d, i) => {
            return {
              id: d.split('__')[0],
              name: d.split('__')[1]
            }
          }),
          keyName: d.keyName.map((dd, ii) => {
            return {
              key: dd.key.split('___')[1],
              name: dd.name
            }
          })
        })
      }
    })
    valuesType = valuesType.filter((dd) => dd.channelIds && dd.channelIds.length > 0)
    if (valuesType.length === 0) {
      message.info('请选择指标和通道')
      return
    }
    if (callback) {
      callback(valuesType, keyNameValue)
    }
  }
  changeDynamicCond () {
    const callback = this.props.callback
    let { kmxMonitors, sensorChannelId, keyNameValue } = this.state
    // kmxMonitors = value ? value : kmxMonitors
    // let monitorKeys = []
    // kmxMonitors.forEach((d) => {
    //   monitorKeys.push(...d.key)
    // })
    // if (monitorKeys.length > 5) {
    //   this.setState({
    //     kmxMonitors: kmxMonitors.slice(0, 4)
    //   })
    //   // message.error('指标数不能大于 5')
    //   return
    // }
    const valuesType = kmxMonitors.map((d, i) => {
      d['channelIds'] = sensorChannelId[d.sensorType].map((d, i) => {
        return d.split('__')[0]
      })
      d['channelNames'] = sensorChannelId[d.sensorType].map((d, i) => {
        return {
          id: d.split('__')[0],
          name: d.split('__')[1]
        }
      })
      return d
    }).filter((dd) => dd.channelIds && dd.channelIds.length > 0)
    if (valuesType.length === 0) {
      message.info('请选择指标和通道')
      return
    }
    if (callback) {
      callback(valuesType, keyNameValue)
    }
  }

  onChanges (values) {
    // let count = 0
    // values.forEach(item => { count += item.key.length })
    // if (count > 5) {
    //   message.error('指标数不能大于 5')
    //   values.forEach((item, index, arr) => {
    //     item.key.forEach((name, indexs) => {
    //       if (name === this.currentValue) {
    //         item.keyName.splice(indexs, 1)
    //         item.key.splice(indexs, 1)
    //       }
    //     })
    //   })
    // }
    // 将key中的En去掉 （En___key）
    const finalValue = values.map((d, i) => {
      return {
        En: d.En,
        sensorType: d.sensorType,
        key: d.key.map((dd, ii) => {
          return dd.split('___')[1]
        }),
        keyName: d.keyName.map((dd, ii) => {
          return {
            key: dd.key.split('___')[1],
            name: dd.name
          }
        })
      }
    })
    this.setState({
      kmxMonitors: finalValue
    })
  }
  onChecked = (checkedKeys, e) => {
  }
  keyNameChange (e) {
    this.setState({
      keyNameValue: e.target.value
    })
  }
  sensorChannelChange (e, d) {
    let obj = {}
    obj[e] = d
    this.setState({
      sensorChannelId: Object.assign({}, this.state.sensorChannelId, obj)
    })
  }
  setCurrentVaule (value, old) {
    this.currentValue = value
    this.oldValue = value
  }
  render () {
    // const { treeData, defaultValue, keyNameValue, channelIds, options, expandedKeys } = this.state
    const { treeData, defaultValue, sensorChannel, sensorChannelId } = this.state
    const expandedKeys = defaultValue[0] ? defaultValue[0].key[0] || '' : ''
    const component = this
    // const { keyName } = this.props
    let content = (
      <div className={styles['popbg']}>
        <div>
          {
            // <h3>键相：</h3>
            // <RadioGroup defaultValue={keyNameValue} onChange={this.keyNameChange}>
            //   {
            //     keyName.map((d, i) => {
            //       return <Radio key={i} value={d}>{d}</Radio>
            //     })
            //   }
            // </RadioGroup>
            // <h3>通道：</h3>
          }
          {
            sensorChannel.map((data, index) => {
              const sensorType = data.sensorType
              let dvalue = sensorChannelId[sensorType]
              /* 动态实现通道的默认选项 */
              // let dvalue = []
              // defaultValue.map((d, i) => {
              //   if (sensorChannelId[d.sensorType]) {
              //     sensorChannelId[d.sensorType].map((dd, ii) => {
              //       dvalue.push(dd.split('__')[0] + '__' + dd.split('__')[1])
              //     })
              //   }
              // })
              /* 设置通道的默认选项是第一项 */
              // dvalue.push(data.channelIds[0]['id'] + '__' + data.channelIds[0]['name'])
              return <div key={index}> {sensorType}通道: <CheckboxGroup defaultValue={dvalue}
                options={
                data.channelIds.map((d, i) => {
                  // if (i === 0) {
                  //   return { label: d.name, value: d.id + '__' + d.name, defaultChecked: true }
                  // } else {
                  //   return { label: d.name, value: d.id + '__' + d.name }
                  // }
                  return { label: d.name, value: d.id + '__' + d.name }
                })
              } onChange={function (value) { component.sensorChannelChange(sensorType, value) }} /></div>
            })
          }
        </div>
        <div className={styles['popCon']}>
          <SelectTree
            expandedKeys={expandedKeys}
            treeData={treeData}
            setCurrentVaule={this.setCurrentVaule}
            onChange={this.onChanges}
            onChecked={this.onChecked}
            defaultValue={defaultValue} />
        </div>
        <p className={styles['popBot']}>
          <Button size='small' type='primary' onClick={this.refer}>确定</Button>
        </p>
      </div>
    )
    return (
      <Popover placement='bottomLeft'
        content={content}
        trigger='click'
        visible={this.state.visible}
        onVisibleChange={this.handleVisibleChange}
      >
        <Button className={styles['button']} type='primary'>选择指标</Button>
      </Popover>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    deviceCard: state.deviceCard,
    deviceFileCondition: state.deviceFileCondition
  }
}
export default connect(mapStatesToProps, { changeHistoryChartCond })(SelectIndicator)
